﻿using Bogus;
using Dapper;
using Dapper.Abstractions;
using Dapper.Bulk;

namespace DataAccess.Api.Endpoints.Blog;

public class Update : IEndpoint
{
    public void MapEndpoint(IEndpointRouteBuilder app)
    {
        // 批量更新示例
        app.MapPost("/api/blogs/bulk-update", async (IDbConnectionFactory dbConnectionFactory) =>
        {
            using var connection = await dbConnectionFactory.CreateConnectionAsync();

            // 首先获取需要更新的现有博客
            const string selectSql = "SELECT * FROM blogs LIMIT 100";
            var existingBlogs = (await connection.QueryAsync<Models.Blog>(selectSql)).ToList();

            if (!existingBlogs.Any())
            {
                return Results.NotFound("No blogs found to update");
            }

            // 使用Bogus更新属性
            var faker = new Faker();
            foreach (var blog in existingBlogs)
            {
                blog.Url = faker.Internet.Url();
            }

            // 配置实体映射
            BulkManager.Entity<Models.Blog>()
                .Table("blogs")
                .Identity(x => x.Id)
                .UseBulkOptions(options =>
                {
                    options.BatchSize = 1000;
                });

            await connection.BulkUpdateAsync(existingBlogs);
            return Results.Ok($"Successfully bulk updated {existingBlogs.Count} blogs");
        })
        .WithName("UpdateBlogs")
        .WithTags(Tags.Blog);
    }
}
